﻿using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Net;
using YFurion.Extensions;

namespace YFurion.Utils.Extensions
{
    public static class HttpContextExtensions
    {
        public static string GetClientIPv4(this HttpContext context)
        {
            if (context == null)
            {
                return "0.0.0.1";
            }
            IHeaderDictionary headers = context.Request.Headers;
            string ip = headers["X-Real-IP"].FirstOrDefault();
            if (ip.IsNullOrWhiteSpace())
            {
                ip = headers["HTTP_X_FORWARDED_FOR"].FirstOrDefault();
            }
            if (ip.IsNullOrWhiteSpace())
            {
                IPAddress ipAddress = context.Connection.RemoteIpAddress;
                ip = ipAddress.MapToIPv4()?.ToString();
            }
            return ip;
        }
    }
}
